package com.javaweb.oa02.web.action;

import com.javaweb.oa02.util.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/dept/list","/dept/add","/dept/edit","/dept/delete","/dept/update","/dept/detail"})
public class Dept extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        //做入口验证，前面往session域中存了username，现在拿出来
        HttpSession session= request.getSession();
        if(session!=null&&session.getAttribute("username")!=null) {
            String servletPath = request.getServletPath();
            if ("/dept/list".equals(servletPath)) {
                doList(request, response);
            } else if ("/dept/add".equals(servletPath)) {
                doAdd(request, response);
            } else if ("/dept/edit".equals(servletPath)) {
                doEdit(request, response);
            } else if ("/dept/update".equals(servletPath)) {
                doUpdate(request, response);
            } else if ("/dept/detail".equals(servletPath)) {
                doDetail(request, response);
            } else if ("/dept/delete".equals(servletPath)) {
                doDel(request, response);
            }
        }else {
            response.sendRedirect(request.getContextPath()+"index.jsp");
        }
}


    /**
     * @description 部门动态（连数据库）数据获取方法
     * @param req  request
     * @param resp response
     * @throws ServletException
     * @throws IOException
     */
    private void doList(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException{
        //String contentPath=req.getContextPath();
        //解决乱码问题
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("UTF-8");

        //创建list集合用于装包装部门信息的user对象
        List<user> list=new ArrayList<>();

        //连接数据库，获取部门信息
        Connection conn= null;
        PreparedStatement ps=null;
        ResultSet rs= null;
        try {
            conn= DButil.getConnection();
            String sql="select * from dept";
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();

            while(rs.next()){

                String deptno=rs.getString("deptno");
                String dname=rs.getString("dname");
                String loc=rs.getString("loc");
                //用user对象来封装部门信息
                user user= new user();
                user.setDeptno(deptno);
                user.setDname(dname);
                user.setLoc(loc);
                //把user对象存入list集合
                list.add(user);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            DButil.close(conn,ps,rs);
        }
        //把装有user对象的list集合存入request域中
        req.setAttribute("userList",list);
        //转发至list.jsp做页面展示
        req.getRequestDispatcher("/list.jsp").forward(req,resp);

    }



    private void doDel(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException{
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("UTF-8");
        //拿到部们编号，用部们编号去删
        String deptno=req.getParameter("deptno");
        Connection conn=null;
        PreparedStatement ps=null;
        int count=0;

        try {
            conn= DButil.getConnection();

            String sql="delete from dept where deptno=?";
            ps=conn.prepareStatement(sql);
            ps.setString(1,deptno);
            count=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(conn,ps,null);
        }
        if(count==1){
            req.getRequestDispatcher("/dept/list").forward(req,resp);
        }else{
            req.getRequestDispatcher("/error.jsp").forward(req,resp);
        }

    }





        private void doDetail(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException{


            // 拿到需要看详情的部门编号
            String deptno = req.getParameter("deptno");
            //解决乱码问题
            resp.setContentType("text/html;charset=utf-8");
            user user = new user();


            Connection conn= null;
            PreparedStatement ps=null;
            ResultSet rs= null;
            try {
                //获取连接
                conn= DButil.getConnection();
                //获取数据库操作对象
                String sql="select deptno,dname,loc from dept where deptno=?";
                ps=conn.prepareStatement(sql);
                ps.setString(1,deptno);
                //编写sql语句
                rs=ps.executeQuery();
                //处理查询结果集
                //String contextPath=req.getContextPath();
                if(rs.next()){
                    String dname=rs.getString("dname");
                    String loc=rs.getString("loc");
                    user.setDeptno(deptno);
                    user.setDname(dname);
                    user.setLoc(loc);
                }

            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                DButil.close(conn,ps,rs);
            }
            req.setAttribute("user",user);
            req.getRequestDispatcher("/detail.jsp").forward(req,resp);

        }

        private void doUpdate(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException{


            //解决乱码问题
            resp.setContentType("text/html;charset=utf-8");
            req.setCharacterEncoding("UTF-8");

            String deptno=req.getParameter("deptno");
            String dname=req.getParameter("dname");
            String loc =req.getParameter("loc");

            Connection conn=null;
            PreparedStatement ps= null;
            int number=0;
            try {
                conn = DButil.getConnection();
                String sql="update dept set dname=?,loc=? where deptno=?";
                ps=conn.prepareStatement(sql);

                ps.setString(1,dname);
                ps.setString(2,loc);
                ps.setString(3,deptno);

                number=ps.executeUpdate();

            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                DButil.close(conn,ps,null);
            }
            //修改后重定向
            if(number!=0){
                resp.sendRedirect(""+req.getContextPath()+"/dept/list");
            }else{
               resp.sendRedirect("/error.jsp");
            }

        }

        private void doEdit(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException{
             //获取servlet路径
           // String contentPath=req.getContextPath();
            //解决字符乱码问题
            resp.setContentType("text/html;charset=UTF-8");
            req.setCharacterEncoding("UTF-8");
            //拿到修改部们的编号
            String deptno=req.getParameter("deptno");


            Connection conn=null;
            PreparedStatement ps= null;
            ResultSet rs=null;

            try {
                conn= DButil.getConnection();
                String sql ="select dname,loc from dept where deptno= ? ";
                ps=conn.prepareStatement(sql);
                ps.setString(1,deptno);
                rs=ps.executeQuery();
                if(rs.next()){
                    String dname=rs.getString("dname");
                    String loc=rs.getString("loc");
                    req.setAttribute("deptno",deptno);
                    req.setAttribute("dname",dname);
                    req.setAttribute("loc",loc);

                }

            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                DButil.close(conn,ps,rs);
            }

            //转发
            req.getRequestDispatcher("/edit.jsp").forward(req,resp);

        }

        private void doAdd(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException{
            //String contentPath=req.getContextPath();
            //解决乱码问题
            resp.setContentType("text/html;charset=utf-8");
            req.setCharacterEncoding("UTF-8");
            //拿到from表单提交的数据
            String deptno=req.getParameter("deptno");
            String dname=req.getParameter("dname");
            String loc=req.getParameter("loc");
            int count=0;

            Connection conn= null;
            PreparedStatement ps=null;
            try {
                conn= DButil.getConnection();
                String sql= "insert into dept(deptno,dname,loc) values(?,?,?)";
                ps=conn.prepareStatement(sql);
                ps.setString(1,deptno);
                ps.setString(2,dname);
                ps.setString(3,loc);
                count=ps.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally{
                DButil.close(conn,ps,null);
            }
            //添加后重定向
            if(count==1){
                resp.sendRedirect(""+req.getContextPath()+"/dept/list");
            }else{
                resp.sendRedirect("/error.jsp");
            }

        }


}
